<template>
  <div class="role__wrapper">
    <!-- 查询 -->
    <div class="role__top">
      <el-form :inline="true" :model="queryForm" ref="queryForm">
        <el-form-item label="菜单名称" prop="roleName">
          <el-input
            placeholder="菜单名称"
            v-model="queryForm.roleName"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="initRoleList">查询</el-button>
          <el-button @click="resetForm('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- /查询 -->
    <!-- 表格 -->
    <div class="role__bottom">
      <div class="active">
        <el-button type="primary" v-has:add="'role-add'" @click="handeAdd"
          >创建</el-button
        >
      </div>
      <el-table :data="roleList" style="width: 100%">
        <el-table-column
          v-for="item in roleCloum"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
          :width="item.width"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template #default="scope">
            <el-button
              size="mini"
              v-has:edit="'role-edit'"
              @click="handeEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              v-has:set="'role-set'"
              @click="handeOpenPermission(scope.row)"
              >设置权限</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="role__page"
        background
        layout="prev, pager, next"
        :total="page.total"
        :page-size="page.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 表格结束 -->
    <!-- 新增表单 -->
    <el-dialog title="新增角色" v-model="showDialog" width="500px">
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            type="text"
            v-model="roleForm.roleName"
            :clearable="true"
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            type="text"
            v-model="roleForm.remark"
            :clearable="true"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handeClose('roleForm')">取 消</el-button>
          <el-button type="primary" @click="handeSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- /新增用户结束 -->
    <!-- 设置权限弹窗 -->
    <el-dialog title="设置权限" v-model="showPermission" width="500px">
      <el-form>
        <el-form-item label="角色名称:">
          {{ curName }}
        </el-form-item>
        <el-form-item label="权限列表:">
          <el-tree
            ref="permisTree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            default-expand-all
            :props="{ label: 'menuName' }"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermission = false">取 消</el-button>
          <el-button type="primary" @click="handePersionSubmit"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- /设置权限弹窗 -->
  </div>
</template>

<script>
import util from '@/utils/utils.js'
export default {
  name: 'Role',
  data () {
    return {
      showDialog: false, // 控制弹出表单
      showPermission: false, // 设置权限弹窗
      queryForm: {}, // 查询表单 
      roleList: [],  // 菜单列表
      roleForm: [],// 表单
      page: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },  // 分页
      roleCloum: [
        {
          prop: 'roleName',
          label: '角色名称',
          width: '150px'
        },
        {
          prop: 'remark',
          label: '备注',
        },
        {
          prop: 'permissionList',
          label: '权限列表',
          formatter: (row, cloum, value) => {
            let names = []
            let list = value.halfCheckedKeys || []
            list.map(key => {
              let name = this.actionMap[key]
              if (key && name) names.push(name)
            })
            return names.join(',')
          }
        },
        {
          prop: 'createTime',
          label: '创建时间',
          formatter (row, cloum, value) {
            return util.formateDate(new Date(value))
          }
        },
      ],// 表格依赖
      rules: {
        roleName: { required: true, message: "请输入菜单名称", trigger: 'blur' }
      }, // 验证
      action: '',  // 表单提交的类型
      curId: '', //设置权限的Id
      curName: '', //设置权限展示的名称,
      menuList: [], // 权限列表
      actionMap: {}, // 菜单映射表
    }
  },
  mounted () {
    this.initRoleList()
    this.getMenuList()
  },
  methods: {
    // 表单重置
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    // 初始化角色数据
    async initRoleList () {
      try {
        const { list, page } = await this.$api.getRoleList({ ...this.queryForm, ...this.page })
        this.roleList = list
        this.page.total = page.total
      } catch (error) {
        throw new Error(error)
      }
    },
    // 获取菜单
    async getMenuList () {
      try {
        let list = await this.$api.getMenuList()
        this.menuList = list
        this.getActionMap(list)
      } catch (error) {
        throw new Error(error)
      }
    },
    // 角色创建
    handeAdd () {
      this.showDialog = true
      this.action = 'add'
      this.handeSubmit()
    },
    // 角色编辑
    handeEdit (row) {
      this.action = 'edit'
      this.showDialog = true;
      this.$nextTick(() => {
        Object.assign(this.roleForm, row)
      })
    },
    // 角色删除
    async handleDelete (_id) {
      try {
        await this.$api.roleSubmit({ _id, action: 'delete' })
        this.initRoleList()
        this.$message.success('删除成功')
      } catch (error) {
        throw new Error(error)
      }
    },
    // 弹框关闭
    handeClose (form) {
      this.resetForm(form)
      this.showDialog = false
    },
    // 角色提交
    handeSubmit () {
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          let { action, roleForm } = this;
          let params = { ...roleForm, action }
          try {
            await this.$api.roleSubmit(params)
            this.handeClose('roleForm')
            this.$message.success('操作成功')
            this.initRoleList()
          } catch (error) {
            throw new Error(error)
          }
        } else {
          return valid
        }
      })
    },
    // 设置权限
    handeOpenPermission (row) {
      this.curName = row.roleName
      this.curId = row._id
      this.showPermission = true;
      let { checkedKeys } = row.permissionList
      setTimeout(() => {
        this.$refs.permisTree.setCheckedKeys(checkedKeys)
      })
    },
    // 权限提交
    async handePersionSubmit () {
      // 选中节点
      let nodes = this.$refs.permisTree.getCheckedNodes()
      // 半选中的节点
      let halfKeys = this.$refs.permisTree.getHalfCheckedKeys()
      // 父元素节点
      let parentKeys = [];
      // 按钮节点
      let checkedKeys = []
      nodes.map(node => {
        if (!node.children) {
          checkedKeys.push(node._id)
        } else {
          parentKeys.push(node._id)
        }
      })
      let params = {
        _id: this.curId,
        permissionList: {
          checkedKeys,
          halfCheckedKeys: parentKeys.concat(halfKeys),
        },
      }
      await this.$api.persionSubmit(params)
      this.showPermission = false;
      this.$message.success('设置成功')
      this.initRoleList()
    },
    // 递归权限列表方法
    getActionMap (list) {
      let actionMap = {}
      const deep = (array) => {
        while (array.length) {
          let item = array.pop()
          // 如果有按钮action 就是最后一层菜单
          if (item.children && item.action) {
            actionMap[item._id] = item.menuName
          }
          if (item.children && !item.action) {
            deep(item.children)
          }
        }
      }
      deep(JSON.parse(JSON.stringify(list)))
      this.actionMap = actionMap
    },
    // 分页
    handleCurrentChange (curren) {
      this.page.pageNum = curren
      this.initRoleList()
    },
  }
}
</script>

<style lang="scss" scoped>
.role__wrapper {
  background: #fff;
}
.role__top {
  height: 0.8rem;
  padding: 0.24rem;
  border-bottom: 0.01rem solid #ebeef1;
}
.role__bottom {
  background: #ebeef1;
  padding-top: 0.3rem;
  .active {
    background: #fff;
    padding: 0.27rem;
  }
  .pages {
    text-align: right;
    padding: 0.1rem 0.27rem;
    background: #fff;
  }
}
</style>